<!DOCTYPE html>

<!-- script标签会把请求过来的响应数据当做JS脚本自动执行 -->
<!-- 已登录，返回：var isLogin = true -->
<!-- 未登录，返回：var isLogin = false -->
<script src="/login/status"></script>
<script>
  // console.log(isLogin, 'isLogin');
  if (!isLogin) {
    location.href = '/admin/login.html'
  }
</script>

<html lang="zh-CN">

<head>
  <meta charset="utf-8">
  <title>Add new post &laquo; Admin</title>
  <link rel="stylesheet" href="/assets/vendors/bootstrap/css/bootstrap.css">
  <link rel="stylesheet" href="/assets/vendors/font-awesome/css/font-awesome.css">
  <link rel="stylesheet" href="/assets/vendors/nprogress/nprogress.css">
  <link rel="stylesheet" href="/assets/css/admin.css">
  <script src="/assets/vendors/nprogress/nprogress.js"></script>
</head>

<body>
  <script>NProgress.start()</script>

  <div class="main">
    <nav class="navbar">
      <button class="btn btn-default navbar-btn fa fa-bars"></button>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="profile.html"><i class="fa fa-user"></i>个人中心</a></li>
        <li><a href="login.html"><i class="fa fa-sign-out"></i>退出</a></li>
      </ul>
    </nav>
    <div class="container-fluid">
      <div class="page-title">
        <h1>编辑文章</h1>
      </div>
      <!-- 有错误信息时展示 -->
      <!-- <div class="alert alert-danger">
        <strong>错误！</strong>发生XXX错误
      </div> -->
      <form class="row" id="editForm">
        <div class="col-md-9">
          <div class="form-group">
            <label for="title">标题</label>
            <input id="title" class="form-control input-lg" name="title" type="text" placeholder="文章标题">
          </div>
          <div class="form-group">
            <label for="content">内容</label>
            <textarea id="content" class="form-control input-lg" name="content" cols="30" rows="10"
              placeholder="内容"></textarea>
          </div>
        </div>
        <div class="col-md-3">
          <div class="form-group">
            <label for="feature">特色图像</label>
            <!-- show when image chose -->
            <img class="help-block thumbnail" style="display: none" id="previewImg">
            <input id="feature" class="form-control" type="file">
            <input type="hidden" name="thumbnail" id="thumbnail">
          </div>
          <div class="form-group">
            <label for="category">所属分类</label>
            <select id="category" class="form-control" name="category"></select>
          </div>
          <!-- <div class="form-group">
            <label for="created">发布时间</label>
            <input id="created" class="form-control" name="created" type="date">
          </div> -->
          <div class="form-group">
            <label for="state">状态</label>
            <select id="state" class="form-control" name="state">
              <option value="0">草稿</option>
              <option value="1">已发布</option>
            </select>
          </div>
          <div class="form-group">
            <button class="btn btn-primary" type="submit">保存</button>
          </div>
        </div>
      </form>
    </div>
  </div>

  <div class="aside">
    <div class="profile">
      <img class="avatar" src="/uploads/avatar.jpg">
      <h3 class="name">Coder</h3>
    </div>
    <ul class="nav">
      <li>
        <a href="index.html"><i class="fa fa-dashboard"></i>仪表盘</a>
      </li>
      <li class="active">
        <a href="#menu-posts" data-toggle="collapse">
          <i class="fa fa-thumb-tack"></i>文章<i class="fa fa-angle-right"></i>
        </a>
        <ul id="menu-posts" class="collapse in">
          <li><a href="posts.html">所有文章</a></li>
          <li class="active"><a href="post-add.html">写文章</a></li>
          <li><a href="categories.html">分类目录</a></li>
        </ul>
      </li>
      <li>
        <a href="comments.html"><i class="fa fa-comments"></i>评论</a>
      </li>
      <li>
        <a href="users.html"><i class="fa fa-users"></i>用户</a>
      </li>
      <li>
        <a href="#menu-settings" class="collapsed" data-toggle="collapse">
          <i class="fa fa-cogs"></i>设置<i class="fa fa-angle-right"></i>
        </a>
        <ul id="menu-settings" class="collapse">
          <li><a href="slides.html">图片轮播</a></li>
          <li><a href="settings.html">网站设置</a></li>
        </ul>
      </li>
    </ul>
  </div>

  <script src="/assets/vendors/jquery/jquery.js"></script>
  <script src="/assets/vendors/bootstrap/js/bootstrap.js"></script>
  <script src="/assets/vendors/art-template/template-web.js"></script>
  <script>NProgress.done()</script>

  <!-- 分类列表模板 -->
  <script type="text/html" id="cateListTpl">
    <option value="">未分类</option>
    {{ each data v }}
    <option value="{{ v._id }}">{{ v.title }}</option>
    {{ /each }}
  </script>

  <script>

    $(() => {

      // 根据id，获取现有数据
      const id = location.search.match(/id=([a-z0-9]+)&?/)[1]
      console.log(id, 'id');


      const $category = $('#category')
      const $feature = $('#feature')
      const $previewImg = $('#previewImg')
      const $thumbnail = $('#thumbnail')
      const $editForm = $('#editForm')

      // 页面一加载，就要获取文章分类数据
      $.ajax({
        type: 'GET',
        url: '/categories',
        // // 将ajax请求变成同步的，也就是，在请求完成前会阻塞后续代码的执行
        // async: false,
        success(res) {
          $category.html(template('cateListTpl', { data: res }))

          // 等待文章分类数据加载完后，再来获取文章详情
          renderPostDetail()
        }
      })

      // 封面文件上传
      $feature.change(({ target }) => {
        const fd = new FormData()
        fd.append('thumbnail', target.files[0])

        $.ajax({
          type: 'POST',
          url: '/upload',
          data: fd,
          processData: false,
          contentType: false,
          success(res) {
            const imgUrl = res[0].thumbnail
            // 预览图片
            $previewImg.attr('src', imgUrl).show()
            // 给隐藏域设置值，为上传成功后的图片路径
            $thumbnail.val(imgUrl)
          }
        })

      })

      // 表单提交
      $editForm.submit(() => {
        const data = $editForm.serialize()
        $.ajax({
          type: 'PUT',
          url: `/posts/${id}`,
          data,
          success(res) {
            alert('编辑成功')
            location.href = '/admin/posts.html'
          }
        })
        return false
      })

      // 渲染文章详情函数
      const renderPostDetail = () => {

        $.ajax({
          type: 'GET',
          url: `/posts/${id}`,
          success(res) {
            console.log(res);
            // 标题
            $('#title').val(res.title)
            // 内容
            $('#content').val(res.content)
            // 封面隐藏域
            $('#thumbnail').val(res.thumbnail)
            // 预览封面
            $previewImg.attr('src', res.thumbnail).show()
            // 分类
            $category.val(res.category)
            // 状态
            $('#state').val(res.state)
          }
        })
      }

    })

  </script>

</body>

</html>